package com.al.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter("/*")
public class CharacterFilter implements Filter {
	private String encode = "UTF-8";
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//从web.xml 配置文件中读取默认编码，如果没有默认编码，默认使用 utf-8
		encode = filterConfig.getInitParameter("encode");
		if(encode == null) {
			encode = "UTF-8";
		}else {
			encode = encode.toUpperCase();
		}
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		if("POST".equalsIgnoreCase(req.getMethod())) {
			req.setCharacterEncoding(encode);
			resp.setCharacterEncoding(encode);
			resp.setContentType("text/html;charset="+encode);
			chain.doFilter(req, resp);
		}
		chain.doFilter(req, resp);
	}
}
